package com.aepryus.loom;

import com.aepryus.util.*;

public abstract class Persist implements Entry {
	abstract public String getName();
	abstract public Domain create () throws PersistenceException;
	abstract public Domain selectByID (long id) throws PersistenceException;
	abstract public Domain[] select (String where) throws PersistenceException;
	abstract public Domain[] select (String where,String orderBy) throws PersistenceException;
	abstract protected void insert (Domain domain) throws PersistenceException;
	abstract protected void update (Domain domain) throws PersistenceException;
	abstract protected void delete (Domain domain) throws PersistenceException;

	public void store (Domain domain) throws PersistenceException {
		if      (domain.getStatus() == Domain.CREATE) insert(domain);
		else if (domain.getStatus() == Domain.EDIT)	  update(domain);
		else if (domain.getStatus() == Domain.DELETE) delete(domain);
	}
	public String unload (Domain domain) {return "";}

// Static ==============================================================================================================
	private static TallyMap ids = new TallyMap();

	public synchronized long getID () throws PersistenceException {
		long id = ids.getTally(getName());
		if (id == 0) {
			id = 1+SQL.queryLong("SELECT MAX("+getName()+"ID) FROM "+getName());
			ids.increment(getName(),id);
		}
		ids.increment(getName());
		return id;
	}
}

